package com.stars.easyms.swagger.handler;

import com.alibaba.fastjson.JSON;
import com.stars.easyms.base.encrypt.EasyMsEncrypt;
import com.stars.easyms.monitor.handler.EasyMsRequestHandler;
import com.stars.easyms.rest.bean.RestInfo;
import com.stars.easyms.rest.constant.RestConstants;
import com.stars.easyms.swagger.constant.EasyMsSwaggerConstants;
import com.stars.easyms.swagger.properties.EasyMsSwaggerProperties;
import com.stars.easyms.base.util.SystemUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * swagger页面跳转控制类
 *
 * @author guoguifang
 * @date 2018-04-23 13:54
 * @since 1.0.0
 */
public class EasyMsSwaggerRequestHandler implements EasyMsRequestHandler {

    private EasyMsSwaggerProperties easyMsSwaggerProperties;

    public EasyMsSwaggerRequestHandler(EasyMsSwaggerProperties easyMsSwaggerProperties) {
        this.easyMsSwaggerProperties = easyMsSwaggerProperties;
    }

    @GetMapping(EasyMsSwaggerConstants.INDEX_URI)
    public void toSwagger(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher("/webjars/easyms/swagger/swagger-ui.html").forward(request, response);
    }

    @PostMapping("/easy-ms/swagger/getSwaggerInfo")
    @ResponseBody
    public Map<String, Object> getSwaggerInfo(HttpServletRequest request) {
        Map<String, Object> returnMap = new HashMap<>(16);
        returnMap.put("title", "Swagger-UI-前后端API接口文档");
        returnMap.put("projectName", "Swagger-Bootstrap-UI RESTful APIs");
        returnMap.put("projectNote", "Swagger-Bootstrap-UI RESTful APIs");
        returnMap.put("projectVersion", "1.0");
        returnMap.put("serverIp", SystemUtil.getHostIp());
        returnMap.put("serverURL", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/");
        returnMap.put("onlineDebug", easyMsSwaggerProperties.isOnlineDebug());
        returnMap.put("easyMsRestUserInfoForSwagger", EasyMsSwaggerConstants.getUserInfoForSwaggerMap());
        returnMap.put("easyMsRestResponseEntityForSwagger", EasyMsSwaggerConstants.getResponseForSwaggerMap());
        return returnMap;
    }

    @PostMapping("/easy-ms/swagger/getApiClassInfo")
    @ResponseBody
    public Map<String, Object> getApiClassInfo(HttpServletRequest request) {
        Map<String, Object> returnMap = new HashMap<>(8);
        String url = request.getParameter("url");
        RestInfo restInfo = RestConstants.REGISTER_REQUEST_MAPPING_PATH_MAP.get(url);
        if (restInfo == null) {
            return returnMap;
        }
        returnMap.put("abbrApiUrl", restInfo.getAbbrRegisterRequestMappingPath());
        returnMap.put("apiType", restInfo.getType().getName());
        returnMap.put("apiServiceClass", restInfo.getRestServiceClass().getCanonicalName());
        if (restInfo.isAllowEndIsForwardSlash()) {
            returnMap.put("allowEndIsForwardSlash", "是");
        }
        if (restInfo.isEncrypt()) {
            returnMap.put("isEncrypt", "是");
            returnMap.put("encryptRequestKey", restInfo.getEncryptRequestKey());
            returnMap.put("encryptResponseKey", restInfo.getEncryptResponseKey());
        } else {
            returnMap.put("isEncrypt", "否");
        }
        return returnMap;
    }

    @PostMapping("/easy-ms/swagger/getEncryptedRequestStr")
    @ResponseBody
    public Object getEncryptedRequestStr(HttpServletRequest request) {
        Map<String, Object> returnMap = new HashMap<>(2);
        String url = request.getParameter("url");
        RestInfo restInfo = RestConstants.REGISTER_REQUEST_MAPPING_PATH_MAP.get(url);
        if (restInfo == null) {
            return returnMap;
        }
        // 为了防止秘钥泄露，只有打开debug模式才可以返回加密后数据，生产环境必须关闭debug模式
        if (easyMsSwaggerProperties.isOnlineDebug() && restInfo.isEncrypt()) {
            String data = request.getParameter("data");
            if (StringUtils.isNotBlank(data)) {
                return EasyMsEncrypt.encrypt(data, restInfo.getSecret(), restInfo.getIv(), restInfo.getEncryptRequestKey());
            }
        }
        return returnMap;
    }

    @PostMapping("/easy-ms/swagger/getDecodedResponseStr")
    @ResponseBody
    public Object getDecodedResponseStr(HttpServletRequest request) {
        Map<String, Object> returnMap = new HashMap<>(2);
        String url = request.getParameter("url");
        RestInfo restInfo = RestConstants.REGISTER_REQUEST_MAPPING_PATH_MAP.get(url);
        if (restInfo == null) {
            return returnMap;
        }
        // 为了防止秘钥泄露，只有打开debug模式才可以返回加密后数据，生产环境必须关闭debug模式
        if (easyMsSwaggerProperties.isOnlineDebug() && restInfo.isEncrypt()) {
            String data = request.getParameter("data");
            if (StringUtils.isNotBlank(data)) {
                String decodedStr = EasyMsEncrypt.decode(data, restInfo.getSecret(), restInfo.getIv(), restInfo.getEncryptResponseKey());
                return new ResponseEntity<>(JSON.parse(decodedStr), HttpStatus.OK);
            }
        }
        return returnMap;
    }

    @GetMapping("/easy-ms/swagger/getErrorCodeInfoByInterfaceNo")
    @ResponseBody
    public Map<String, Object> getErrorCodeInfoByInterfaceNo() {
        return null;
    }

}
